<template>
  <el-table :data="tableData" stripe style="width: 100%" border @row-click="handleRowClick">
    <el-table-column label="博客动态" align="center">
      <template #default="scope">
        <div class="weibo-card">
          <!-- 头像及发布者信息区域 -->
          <div class="weibo-card__header">
            <div class="avatar-container">
              <img :src="'/img'+scope.row.tx" alt="avatar" class="weibo-card__avatar" />
              <span class="weibo-card__nickname">{{ scope.row.nc }}</span>
            </div>
            <div class="header-content">
              <div class="weibo-card__meta">
                {{ scope.row.time }} 来自 博客网页版
              </div>
              <div class="weibo-card__meta">
                标题# {{ scope.row.title }}
              </div>
            </div>
            <div class="follow-container" style="margin-left: auto;" v-if="userId !== scope.row.userId">
              <el-button
                  size="small"
                  :type="scope.row.isFollowed ? 'info' : 'primary'"
                  @click.stop="handleFollow(scope.row)"
                  round
                  style="color: orange; --el-button-hover-bg-color:#fcf0de; --el-button-bg-color: #fff; --el-button-color: #ff6b6b; --el-button-hover-border-color: #ee0d64;--el-button-border-color: orange;"

              >
                {{ scope.row.isFollowed ? '已关注' : '+关注' }}
              </el-button>
            </div>
          </div>

          <!-- 动态内容区域 -->
          <div class="weibo-card__content">
            {{ scope.row.text }}
            <div class="weibo-card__image" v-if="scope.row.url && scope.row.url.trim()">
              <img
                  v-for="(imgUrl, index) in scope.row.url.split(',')"
                  :key="index"
                  :src="'/img'+imgUrl.trim()"
                  alt="weibo-img"
                  class="imgs"
              />
            </div>
            <!-- 视频展示 -->
            <div class="weibo-card__video" v-if="scope.row.video && scope.row.video.trim()">
              <video
                  v-for="(videoUrl, index) in scope.row.video.split(',')"
                  :key="'video-'+index"
                  :src="'/img'+videoUrl.trim()"
                  controls
                  class="video-player"
              >您的浏览器不支持视频播放</video>
            </div>
          </div>

          <!-- 互动按钮区域（含点赞/收藏状态） -->
          <div class="weibo-card__actions">
            <span class="weibo-card__action">
              <el-icon class="el-icon"><ChatDotRound /></el-icon>
              {{ scope.row.commentCount || 0 }}
            </span>

            <!-- 点赞按钮（带状态） -->
            <span class="weibo-card__action" @click="handleLike(scope.row)">
              <el-icon class="el-icon" :class="{ 'liked': scope.row.isLiked }"><Pointer /></el-icon>
              {{ scope.row.likeCount || 0 }}
            </span>

            <!-- 收藏按钮（带状态） -->
            <span class="weibo-card__action" @click="handleCollect(scope.row)">
              <el-icon class="el-icon" :class="{ 'collected': scope.row.isCollected }"><StarFilled /></el-icon>
              {{ scope.row.collectCount || 0 }}
            </span>

            <span class="weibo-card__action">
              <el-icon class="el-icon"><View /></el-icon>
              {{ scope.row.browse || 0 }}
            </span>
          </div>
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { ChatDotRound, StarFilled, View, Pointer } from '@element-plus/icons-vue';
import router from "../router";
import { useUserStore } from "@/stores/user";

// 用户信息（获取当前登录用户ID）
const userStore = useUserStore();
const userId = userStore.id;

// 帖子列表数据（每个帖子包含独立的点赞/收藏状态）
const tableData = ref([]);

// 页面加载时初始化数据
onMounted(() => {
  // 加载帖子列表后立即初始化所有帖子的状态
  doListWithAllCount().then(() => {
    initAllPostStatus();
  });
});

/**
 * 加载帖子列表数据
 * 为每个帖子添加isLiked和isCollected初始状态
 */
const doListWithAllCount = async () => {
  const { data } = await axios.get('/api/postAndUser/allCountAndOrderedByTime');
  // 为每个帖子初始化点赞/收藏状态（默认未操作）
  tableData.value = data.map(post => ({
    ...post,
    isLiked: false,
    isCollected: false,
    isFollowed: false // 添加关注状态初始化
  }));
  return tableData.value;
};

/**
 * 初始化所有帖子的点赞/收藏状态
 * 遍历列表调用接口查询每个帖子的状态
 */
const initAllPostStatus = async () => {
  if (!userId) return; // 未登录则不初始化状态
  for (const post of tableData.value) {
    // 并行请求当前帖子的点赞和收藏状态（优化加载速度）
    await Promise.all([
      getLikeStatus(post),
      getCollectStatus(post),
      getFollowStatus(post)
    ]);
  }
};

/**
 * 获取单个帖子的点赞状态
 */
const getLikeStatus = async (post) => {
  const postId = post.id;
  if (!postId) return;
  const { data: likeData } = await axios.get(`/api/like/${postId}/${userId}`);
  post.isLiked = !!likeData; // 存在记录则标记为已点赞

};

/**
 * 获取单个帖子的收藏状态
 */
const getCollectStatus = async (post) => {
  const postId = post.id;
  if (!postId) return;

  const { data: status } = await axios.get(`/api/collect/status/user/${userId}/post/${postId}`);
  post.isCollected = status; // 直接使用后端返回的布尔值
};

/**
 * 处理点赞操作
 */
const handleLike = async (post) => {
  const postId = post.id;
  if (!postId || !userId) {
    alert("请先登录");
    return;
  }


  if (post.isLiked) {
    // 取消点赞
    const res = await axios.delete(`/api/like/${postId}/${userId}`);
    if (res.data > 0) {
      post.isLiked = false;
      post.likeCount = (post.likeCount || 0) - 1;
    }
  } else {
    // 新增点赞
    const likeData = {
      postId: postId,
      userId: userId,
      time: new Date().toISOString().replace('T', ' ').slice(0, 19)
    };
    const res = await axios.post('/api/like', likeData);
    if (res.data > 0) {
      post.isLiked = true;
      post.likeCount = (post.likeCount || 0) + 1;
    }
  }
};

/**
 * 处理收藏操作
 */
const handleCollect = async (post) => {
  const postId = post.id;
  if (!postId || !userId) {
    alert("请先登录");
    return;
  }

  if (post.isCollected) {
    // 取消收藏：先查询收藏ID再删除
    const { data: collectId } = await axios.get(`/api/collect/user/${userId}/post/${postId}`);
    if (!collectId) {
      alert("未找到收藏记录");
      return;
    }
    const res = await axios.delete(`/api/collect/${collectId}`);
    if (res.data > 0) {
      post.isCollected = false;
      post.collectCount = (post.collectCount || 0) - 1;
    }
  } else {
    // 新增收藏
    const collectData = {
      userId: userId,
      postId: postId,
      time: new Date().toISOString().replace('T', ' ').slice(0, 19)
    };
    const res = await axios.post('/api/collect', collectData);
    if (res.data > 0) {
      post.isCollected = true;
      post.collectCount = (post.collectCount || 0) + 1;
    }
  }
};

/**
 * 获取单个帖子的关注状态
 */
const getFollowStatus = async (post) => {
  const targetUserId = post.userId;
  if (!targetUserId || !userId || userId === targetUserId) return;

  try {
    const { data } = await axios.get(`/api/relations/${userId}/${targetUserId}`);
    console.log('请求成功:', data); //
    post.isFollowed = !!data; // 后端返回布尔值
  } catch (error) {
    console.error('获取关注状态失败:', error);
    post.isFollowed = false;
  }
};

/**
 * 处理关注操作
 */
const handleFollow = async (post) => {
  const targetUserId = post.userId;
  if (!targetUserId || !userId || userId === targetUserId) {
    alert("无法关注自己或请先登录");
    return;
  }

  try {
    if (post.isFollowed) {
      // 取消关注
      const res = await axios.delete(`/api/relation/${userId}/${targetUserId}`);
      if (res.data > 0) {
        post.isFollowed = false;
      }
    } else {
      // 添加关注
      const followData = {
        fanId: userId,
        userId: targetUserId
      };
      const res = await axios.post('/api/relation', followData);
      if (res.data > 0) {
        post.isFollowed = true;
      }
    }
  } catch (error) {
    console.error('关注操作失败:', error);
    alert('操作失败');
  }
};


/**
 * 点击行跳转至帖子详情页
 */
const handleRowClick = (row) => {
  router.push(`/poster?id=${row.id}`);
};
</script>

<style scoped>
.weibo-card {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.weibo-card__header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.avatar-container {
  display: flex;
  align-items: center;
}

.weibo-card__avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 8px;
}

.weibo-card__nickname {
  font-weight: bold;
  color: #333;
  margin-right: 8px;
}

.header-content {
  display: flex;
  flex-direction: column;
}

.weibo-card__meta {
  font-size: 12px;
  color: #999;
}

.weibo-card__content {
  margin: 8px 0;
  color: #333;
  line-height: 1.6;
}

.weibo-card__image {
  margin-top: 8px;
  /* 删掉 display: flex; gap: 4px; flex-wrap: wrap; */
}
.imgs {
  width: 180px;
  height: 180px;
  margin: 0 2px;
  /* 删掉 object-fit: cover;（如果不需要图片裁剪） */
  border-radius: 4px; /* 保留圆角，和详情页一致 */
}
.weibo-card__actions {
  display: flex;
  gap: 24px;
  color: #666;
  margin-top: 12px;
  justify-content: center;
}

.weibo-card__action {
  display: flex;
  align-items: center;
  gap: 4px;
  transition: color 0.2s;
  cursor: pointer;
}

.weibo-card__action:hover {
  color: #409eff;
}

.el-icon {
  font-size: 20px;
}

/* 点赞和收藏状态样式 */
::v-deep .weibo-card__action .liked {
  color: #ff4d4f; /* 点赞后红色 */
}

::v-deep .weibo-card__action .collected {
  color: #faad14; /* 收藏后金色 */
}
.weibo-card__video {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}
.video-player {
  max-width: 100%;
  max-height: 400px;
  border-radius: 4px;
  background-color: #000;
  outline: none;
}
</style>
